package com.company.ui;

import com.company.MyLinkList;
import com.company.StudentTable;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;

/**
 * Created by v on 16-12-20.
 */
public class UI extends JFrame{
    private StudentUI studentUI;
    private TableUI tableUI;
    private MyLinkList<StudentTable> tables;
    private File file=new File("Student.data");

    public UI(){
        init();
        studentUI=new StudentUI();
        tableUI=new TableUI(studentUI,tables);

        setLayout(new BorderLayout());

        add(studentUI,BorderLayout.CENTER);
        add(tableUI,BorderLayout.WEST);
    }


    public static void main(String[] args) {
        JFrame ui=new UI();

        ui.setVisible(true);
        ui.setSize(1000,600);
        ui.setLocation(100,50);
        ui.setTitle("学生健康管理系统");
        ui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void init(){
        tables=new MyLinkList<>();

        try{
            if(!file.exists()){
                file.createNewFile();
            }

            ObjectInputStream input=new
                    ObjectInputStream(new FileInputStream(file));

                tables=(MyLinkList<StudentTable>) input.readObject();
            input.close();
        }catch (IOException ex){
            ex.printStackTrace();
        }catch (ClassNotFoundException ex){
            ex.printStackTrace();
        }

        //这个监听器用于在关闭时保存数据
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);

                try{
                    file.createNewFile();

                    ObjectOutputStream ouput= new
                            ObjectOutputStream(new FileOutputStream(file));

                    ouput.writeObject(tables);
                    ouput.close();
                }catch (IOException ex){

                }
            }
        });
    }
}
